# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message: 获取保养表
from untils.MysqlTools import MysqlTools
import json

class GetMaintenancePartNum:

    def __init__(self, **kwargs):
        self.m_db = MysqlTools(db_config=kwargs.get("m_db"), type='dict', auto_commit=1000)
        self.p_db = MysqlTools(db_config=kwargs.get("p_db"), type='dict', auto_commit=1000)
        self.brandCode = kwargs.get("brandCode")
        self.m_part_table = kwargs.get("m_part_table")
        self.part_num_table = kwargs.get("part_num_table")
        self.structure_table = kwargs.get("structure_table")
        self.group_table = kwargs.get("group_table")
        self.maintenance_part_num_table = kwargs.get("maintenance_part_num_table")
        self.struct_extra_info_dict = {}

    def construct_insert_sql(self, table, data, db=None):
        fields = '`' + '`,`'.join(data.keys()) + '`'
        values = []
        for v in data.values():
            if v == 0:
                v = '0'
            elif not v:
                v = ''
            if type(v) == int:
                values.append(v.__str__())
            elif v == "now()":
                values.append(v)
            else:
                values.append("'%s'" % v.replace("'", " ").replace("\\", "\\\\"))
        if db:
            sql = 'INSERT INTO `%s`.`%s` (%s) VALUES (%s)' % (db, table, fields, ",".join(values))
        else:
            sql = 'INSERT INTO `%s` (%s) VALUES (%s)' % (table, fields, ",".join(values))
        return sql

    def get_m_part_data(self):
        sql = '''select * from {}'''.format(self.m_part_table)
        data = self.m_db.select_all(sql)
        return data

    def get_part_num_dict(self, m_data):
        pid_list = tuple([i.get("pid") for i in m_data])
        sql = '''select * from `{}` where `pid` in {}'''.format(self.part_num_table, pid_list)
        data = self.p_db.select_all(sql)
        _dict = {}  # {pid:{brandCode1:[i, i, i], brandCode2:[i, i]}, pid2:{brandCode:[i, i]}}
        for i in data:
            pid = i.get("pid")
            brandCode = i.get("brandCode")
            k = pid
            if k not in _dict:
                _dict[k] = {brandCode:[i]}
            else:
                if brandCode not in _dict[k]:
                    _dict[k][brandCode] = [i]
                else:
                    _dict[k][brandCode].append(i)
        return _dict

    def get_struct_extra_info_dict(self):
        sql = '''select cid,mid,brandCode,extra_info from {}'''.format(self.structure_table)
        if self.brandCode == 'bmw':
            sql = '''select cid,subgroup as mid,brandCode,extra_info from {}'''.format(self.structure_table)
        data = self.p_db.select_all(sql)
        # self.struct_extra_info_dict = {}
        for i in data:
            cid = i.get("cid")
            mid = i.get("mid")
            brandCode = i.get("brandCode")
            extra_info = i.get("extra_info")
            k = cid+'_'+mid+'_'+brandCode
            self.struct_extra_info_dict[k] = extra_info

    def get_struct_extra_info(self, cid, mid, brandCode):
        k = cid + '_' + mid + '_' + brandCode
        info = self.struct_extra_info_dict.get(k, '')
        return info

    def get_struct_extra_info_new(self, cid, mid, brandCode):
        sql = 'select extra_info from {} where cid="{}" and mid="{}" and brandCode="{}"'.format(self.structure_table, cid, mid, brandCode)
        data = self.p_db.select_one(sql)
        try:
            extra_info = data.get("extra_info")
        except Exception as e:
            print(sql)
            extra_info = json.dumps({})
        return extra_info

    def get_group_struct_extra_info(self, cid, mid, brandCode):
        sql = 'select extra_info,num from {} where cid="{}" and mid="{}" and brandCode="{}" limit 1'.format(self.structure_table, cid, mid, brandCode)
        data = self.p_db.select_one(sql)
        if not data:
            return ""
        # return data['extra_info']
        num = data['num']  # 获取num
        group_sql = '''select extra_info from {} where num="{}" and cid="{}" limit 1'''.format(self.group_table, num, cid)
        group_data = self.p_db.select_one(group_sql)  # 去cars_group_collection查询对应的extra_info
        if not group_data:  # 如果没有查询到,返回开始的data['extra_info']
            return data['extra_info']
        # 如果查询到内容,把内容添加到开始的data['extra_info'],新建字段名为group_extra_info
        dict_data = json.loads(data['extra_info'])
        dict_data['group_extra_info'] = json.loads(group_data['extra_info'])  # 把新查询出来的extra_info添加到原有的extra_info字典中

        return json.dumps(dict_data)

    def create_maintenance_row(self, part_info, m):
        cid = part_info.get("cid")
        mid = part_info.get("mid")
        brandCode = part_info.get("brandCode")
        if self.brandCode in ['land_rover','jaguar']:
            struct_extra_info = self.get_group_struct_extra_info(cid, mid, brandCode)
        else:
            struct_extra_info = self.get_struct_extra_info_new(cid, mid, brandCode)
        _dict = dict(
            m_type=m.get("m_type"),  # 保养类型
            # pid = m.get("pid"),  # 零件号
            standard_label=m.get("standard_label"),  # 零件标准名称
            sequence=m.get("sequence"),  # 排序序号(已取消)
            cid=part_info.get("cid",''),
            num=part_info.get("num",''),
            mid=part_info.get("mid",''),
            itid=part_info.get("itid",''),
            psort=part_info.get("psort",''),
            brandCode=part_info.get("brandCode",''),
            pid=part_info.get("pid",''),
            label=part_info.get("label",''),
            remark=part_info.get("remark",''),
            quantity=part_info.get("quantity",''),
            model=part_info.get("model",''),
            condition=part_info.get("condition",''),
            extra_info=part_info.get("extra_info",''),
            struct_extra_info=struct_extra_info,
            updatetime='now()',
            createtime='now()',
            # status='',
            # man_hour='',
            # process='',
        )
        if self.brandCode in ['bullstuff','ferrari','maserati']:  # 没有psort字段
            _dict.pop('psort')

        in_sql = self.m_db.get_insert_sql(self.maintenance_part_num_table, _dict)
        # print(in_sql)
        try:
            self.m_db.execute_sql(in_sql)
        except Exception as e:
            print(in_sql)
            raise e

    def get_p_data(self,pid):
        sql = '''select * from `{}` where `pid`="{}"'''.format(self.part_num_table, pid)
        data = self.p_db.select_all(sql)
        _dict = {}
        for i in data:
            brandCode = i.get("brandCode")
            if brandCode not in _dict:
                _dict[brandCode] = [i]
            else:
                _dict[brandCode].append(i)
        return _dict

    def run(self):
        m_part_data = self.get_m_part_data()
        # part_num_dict = self.get_part_num_dict(m_part_data)
        # self.get_struct_extra_info_dict()
        print("开始循环...")
        for m in m_part_data:
            # m_type = m.get("m_type")  # 保养类型
            pid = m.get("pid")  # 零件号
            # standard_label = m.get("standard_label")  # 零件标准名称
            # sequence = m.get("sequence")  # 排序序号(已取消)
            # p_data = part_num_dict.get(pid)
            p_data = self.get_p_data(pid)
            if not p_data:
                print('{}:当前零件号不存在与零件表中'.format(pid))
                continue
            for b in p_data:
                brandCode = b
                part_list = p_data.get(brandCode)
                for part_info in part_list:
                    self.create_maintenance_row(part_info, m)
        self.m_db.commit_sql()
        self.p_db.commit_sql()

if __name__ == '__main__':
    m_db = dict(  # m_part表及保养表的数据库配置
        host="192.168.10.166",
        port=3306,
        user="a",
        passwd="110",
        db="audi",
        charset="utf8",
    )
    p_db = dict(  # 零件及分组表的数据库配置
        host="192.168.10.166",
        port=3306,
        user="a",
        passwd="110",
        db="audi",
        charset="utf8",
    )
    brandCode = 'audi'  # 品牌
    m_part_table = 'audi_m_part'
    part_num_table = 'cars_part_num'
    structure_table = 'cars_structure_collection'
    group_table = 'cars_group_collection'
    maintenance_part_num_table = 'maintenance_part_num_audi_repair'
    tools = GetMaintenancePartNum(m_db=m_db,p_db=p_db,brandCode=brandCode,m_part_table=m_part_table,part_num_table=part_num_table,structure_table=structure_table,group_table=group_table,maintenance_part_num_table=maintenance_part_num_table)
    tools.run()